using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using RestaurantFinder.Web.Data;
using RestaurantFinder.Core.Services;
using RestaurantFinder.Infrastructure.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<WeatherForecastService>();

// 🗃️ 添加内存缓存服务
builder.Services.AddMemoryCache(options =>
{
    // 设置缓存大小限制为更大的值，以字节为单位（10MB）
    options.SizeLimit = builder.Configuration.GetValue<long>("Cache:MaxCacheSizeBytes", 10 * 1024 * 1024);
    
    // 启用压缩后清理，当内存压力大时自动清理
    options.CompactionPercentage = 0.25; // 清理25%的条目
});

// 🔧 配置HttpClient服务
builder.Services.AddHttpClient<IGaodeMapService, GaodeMapService>(client =>
{
    var timeout = builder.Configuration.GetValue<int>("GaodeMap:RequestTimeout", 30);
    client.Timeout = TimeSpan.FromSeconds(timeout);
    client.DefaultRequestHeaders.Add("User-Agent", "RestaurantFinder/1.0");
});

// 🏗️ 注册业务服务 - .NET 8 最佳实践
builder.Services.AddScoped<IGaodeMapService, GaodeMapService>();
builder.Services.AddScoped<ISearchCacheService, MemorySearchCacheService>();
builder.Services.AddScoped<IRestaurantService, SmartRestaurantService>();
builder.Services.AddScoped<IPageStateService, BrowserPageStateService>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

// 🏥 添加健康检查端点
app.MapGet("/health", () => Results.Ok(new { 
    status = "healthy", 
    timestamp = DateTimeOffset.UtcNow,
    version = "1.0.0"
}));

// 🔧 添加诊断端点
app.MapGet("/api/diagnostics", (IConfiguration config, ILogger<Program> logger) =>
{
    try
    {
        var gaodeEnabled = config.GetValue<bool>("GaodeMap:Enabled", false);
        var hasApiKey = !string.IsNullOrEmpty(config["GaodeMap:ApiKey"]);
        var cacheEnabled = config.GetValue<bool>("Cache:Enabled", false);
        
        var apiKey = config["GaodeMap:ApiKey"];
        var diagnostics = new
        {
            timestamp = DateTimeOffset.UtcNow,
            environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"),
            gaodeMap = new
            {
                enabled = gaodeEnabled,
                hasApiKey = hasApiKey,
                apiKeyLength = apiKey?.Length ?? 0,
                apiKeyPrefix = apiKey?.Length > 8 ? apiKey.Substring(0, 8) + "..." : apiKey,
                baseUrl = config["GaodeMap:BaseUrl"],
                requestTimeout = config.GetValue<int>("GaodeMap:RequestTimeout", 30)
            },
            cache = new
            {
                enabled = cacheEnabled,
                maxSizeBytes = config.GetValue<long>("Cache:MaxCacheSizeBytes", 0)
            },
            status = gaodeEnabled && hasApiKey ? "ready" : "using_mock_data"
        };
        
        logger.LogInformation("诊断信息已查询: GaodeEnabled={GaodeEnabled}, HasApiKey={HasApiKey}", 
            gaodeEnabled, hasApiKey);
            
        return Results.Ok(diagnostics);
    }
    catch (Exception ex)
    {
        logger.LogError(ex, "获取诊断信息失败");
        return Results.Problem("诊断信息获取失败");
    }
});

app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();
